__author__ = 'ville'
#coding=UTF-8
import random
import urllib2
import json
import sys
import time
import threading
reload(sys)
sys.setdefaultencoding("utf-8")

#URL_SHENTONG = "http://www.kiees.cn/sto.php?wen=%s&ajax=1&rnd=%s"
URL_SHENTONG = "http://www.kuaidi100.com/query?type=%s&postid=%s&id=1&valicode=&temp=%s"
STOP_FLAG = False
'''
http://www.kiees.cn/sto.php?wen=768685345163&ajax=1&rnd=0.005095247644931078
http://www.kuaidi100.com/query?type=shentong&postid=768685345160&id=1&valicode=&temp=0.745760798221454
http://baidu.kuaidi100.com/query?type=shentong&postid=768166348820&id=4&valicode=%E9%AA%8C%E8%AF%81%E7%A0%81&temp=0.45086159580387175&sessionid=A8C27A01065E0277C5E8E53D668B9751
'''

class QueryThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.req_list = []

    def _query_one(self, com, num):
        query_kuaidi100(com, num)

    def set_req_list(self, _req_list):
        self.req_list = _req_list
        return

    def run(self):
        print "======= Start Thread ============"
        print self.req_list
        self._start_auto_query(self.req_list)

    def _start_auto_query(self, req_list):
        """
        req_list is like
        [{"com": "shentong", "from": "768685345059", "to": "768685345080"},
        {"com": "zhongtong", "from": "761303087904", "to": "761303087910"}]
        """
        for _dict in req_list:
            if STOP_FLAG:
                break
            self._start_auto_query_one_com(_dict)
        return

    def _start_auto_query_one_com(self, _dict):
        """
        _dict is like {"com": "shentong", "from": "768685345059", "to": "768685345080"}
        """
        _com = _dict["com"]
        _from = int(_dict["from"])
        # +1 is Important
        _to = int(_dict["to"]) + 1
        for x in range(_from, _to):
            if STOP_FLAG:
                break
            self._query_one(_com, x)
            time.sleep(4.0)
        return

    def stop(self):
        return


def start_query_one(com, num):
    global STOP_FLAG
    STOP_FLAG = False
    _list = [{"com": com, "from": num, "to": num}]
    worker = QueryThread()
    worker.set_req_list(_list)
    worker.start()

def start_query_com_all(com, _from, _to):
    global STOP_FLAG
    STOP_FLAG = False
    _list = [{"com": com, "from": _from, "to": _to}]
    worker = QueryThread()
    worker.set_req_list(_list)
    worker.start()


def start_auto_query(_req_list):
    global STOP_FLAG
    STOP_FLAG = False
    worker = QueryThread()
    worker.set_req_list(_req_list)
    worker.start()


def stop_query():
    global STOP_FLAG
    STOP_FLAG = True


def getHtml(url):
    #socket.setdefaulttimeout(10)
    #print "Begin To Get Html :: " + url
    html = ""
    try:
        req = urllib2.Request(url)
        req.add_header("User-Agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11")
        req.add_header("Accept", "*/*")
        req.add_header("Accept-Language", "zh-CN,zh;q=0.8")
        page = urllib2.urlopen(req, None, 8.0)
        html = page.read().decode("utf-8", 'ignore').encode("utf-8")
    except urllib2.URLError, e:
        print "URL Error : %r" % e
    except Exception, e:
        #print "Exception: ", e
        return
    #else:
        #print "Get Html Success!! :: "
    return html


def query_kuaidi100(com, num):
    rnd = str(random.random())
    #print "Start %s : %s" % (num, rnd)
    url = URL_SHENTONG % (str(com), str(num), str(rnd))
    content = getHtml(url)
    #print "Get ===> " + content
    if content is None or content == "":
        print "%s - %s Error" % (com, num)
    else:
        #print content
        json_str = json.loads(content)
        status = int(json_str["status"])
        if status == 200:
            com = parse_com(json_str["com"])
            nu = str(json_str["nu"])
            state = parse_state(int(json_str["state"]))
            data = json_str["data"]
            lastest = {"time": "unknow", "context": "unknow"}
            earlist = {"time": "unknow", "context": "unknow"}
            if len(data) > 0:
                lastest["time"] = str(data[0]["time"])
                lastest["context"] = str(data[0]["context"])
                end = len(data) - 1
                earlist["time"] = str(data[end]["time"])
                earlist["context"] = str(data[end]["context"])

            print "%s - %s - %s  #[%s %s]  <==== [%s]" % (com, nu, state, str(lastest["time"]), str(lastest["context"]), str(earlist["context"]))
        elif status == 403:
            print "[Error] %s - %s #%s" % (parse_com(com), str(num), json_str['message'])
        elif status == 201:
            print "[Error] %s - %s #%s" % (parse_com(com), str(num), json_str['message'])


def parse_state(state):
    """
    0：在途，即货物处于运输过程中；
    1：揽件，货物已由快递公司揽收并且产生了第一条跟踪信息；
    2：疑难，货物寄送过程出了问题；
    3：签收，收件人已签收；
    4：退签，即货物由于用户拒签、超区等原因退回，而且发件人已经签收；
    5：派件，即快递正在进行同城派件；
    6：退回，货物正处于退回发件人的途中；
    """
    if state == 0:
        return "在途"
    elif state == 1:
        return "揽件"
    elif state == 2:
        return "疑难"
    elif state == 3:
        return "签收"
    elif state == 4:
        return "退签"
    elif state == 5:
        return "派件"
    elif state == 6:
        return "退回"

dic_com_word = {"shentong": "申通", "yuantong": "圆通", "zhongtong": "中通"}
def parse_com(com):
    if com == "shentong":
        return "申通"
    elif com == "yuantong":
        return "圆通"
    elif com == "zhongtong":
        return "中通"
    return com

#query_kuaidi100("shentong", 768685345059)
#query_kuaidi100("zhongtong", 761303087904)
#query_kuaidi100("zhongtong", 761303055405)
#auto_query("shentong", 768685345189, 768685345259)message
#auto_query("shentong", 768685345059, 768685345259)

#start_query_one("zhongtong", 761303055405)
#start_query_com_all("zhongtong", 761303055405, 761303055415)
_req_list = [{"com": "shentong", "from": "768685345059", "to": "768685345066"},
             {"com": "zhongtong", "from": "761303055405", "to": "761303055411"}]
start_auto_query(_req_list)
